package com.deluxelx.rmo.essay.service;

import cn.hutool.core.util.ObjectUtil;
import com.deluxelx.rmo.common.constants.DecisionKey;
import com.deluxelx.rmo.common.enums.GenderCode;
import com.deluxelx.rmo.essay.domain.rule.engine.EngineFilter;
import com.deluxelx.rmo.essay.mapper.EssayMapper;
import com.deluxelx.rmo.essay.api.vo.EssayVo;
import com.deluxelx.rmo.essay.model.req.DecisionMakingReq;
import com.deluxelx.rmo.essay.model.res.DecisionMakingRes;
import com.deluxelx.rmo.essay.api.res.EssayRes;
import com.deluxelx.rmo.essay.api.EssayService;
import com.deluxelx.rmo.user.api.dto.UserSentimentDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EssayServiceImpl implements EssayService {

    @Resource
    private EngineFilter engineFilter;

    @Resource
    private EssayMapper essayMapper;

    @Override
    public EssayRes<List<EssayVo>> defaultRecommendEssay() {
        List<EssayVo> essayVoList = essayMapper.getHotEssayDto();
        return EssayRes.buildSuccessResult(essayVoList);
    }

    @Override
    @Transactional
    public EssayRes<List<EssayVo>> recommendEssayBySentiment(Long treeId, UserSentimentDto userSentiment) {
        if (ObjectUtil.equals(userSentiment.getSentiment(), -1L) && ObjectUtil.equals(userSentiment.getGender(), -1)) {
            // 如果用户仅仅只是注册了一个 User，未进行任何更改操作的话，也是直接返回热点文章
            return EssayRes.buildSuccessResult(essayMapper.getHotEssayDto());
        }
        // 1. 发出决策请求
        DecisionMakingReq req = new DecisionMakingReq();
        req.setTreeId(treeId);
        req.setUserId(userSentiment.getUserId());
        req.setValMap(new HashMap<String, Object>() {
            {
                put(DecisionKey.USER_GENDER, GenderCode.getInfoByCode(userSentiment.getGender()));
                put(DecisionKey.USER_SENTIMENT, userSentiment.getSentiment());
            }
        });
        // 2. 得到决策结果
        DecisionMakingRes res = engineFilter.process(req);
        // 3. 解析决策结果
        String[] labelIdsStr = res.getNodeValue().split(",");
        List<Long> labelIds = Arrays.stream(labelIdsStr).map(Long::valueOf).collect(Collectors.toList());
        // 4. 根据结果寻找相应文章
        List<EssayVo> essayVoList = essayMapper.getHotEssayDtoListByLabel(labelIds);
        return EssayRes.buildSuccessResult(essayVoList);
    }

}
